
//
// 110619 - AH - (Fotballpuben *) Created.
// 110621 - AH - (Zen *) Finished implementation.
//

package org.soekrat.engine.io.xmlutil;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

/**
 * <p>
 *   Object that writes start and end of a XML document: The 'top' of the 
 *   content hierarchy.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
public class XmlTopContentGenerator 
{
  private final String m_topElement;
  
  /**
   * <p>
   *   Constructor.
   * </p>
   * @param topElement {@link #getTopElement()}.
   */
  public XmlTopContentGenerator(String topElement)
  {
    if (topElement==null)
    {
      throw new NullPointerException("topElement");
    }
    
    m_topElement=topElement;  
  }
  
  /**
   * <p>
   *   Gets name on XML dialect's top element.
   * </p>
   * @return Element name.
   */
  public final String getTopElement(){ return m_topElement; }
  
  /**
   * <p>
   *   Gets first line in a XML file, the XML declaration.
   * </p>
   * <p>
   *   Default implementation returns {@code <?xml version='1.0' ?>}.
   * </p>
   * @return What to write first.
   */
  protected String getXmlDecl(){ return "<?xml version='1.0' ?>"; } 
  
  /**
   * <p>
   *   Gets text that is start of XML file.
   * </p>
   * <p>
   *   Default implementation simple write first what 
   *   {@link #getXmlDecl()} returns then start element named
   *   {@link #getTopElement()}.
   * </p>
   * @return Compiled.
   */
  public String getStart()
  {
    CharArrayWriter caw=new CharArrayWriter();
    PrintWriter pw=new PrintWriter(caw);
    
    pw.println(getXmlDecl());
    pw.print("<");
    pw.print(m_topElement);
    pw.println(">");
    
    pw.flush();
    String s=caw.toString();
    
    return s;
  }
  
  /**
   * <p>
   *   Gets text that is start of XML file.
   * </p>
   * @return Compiled.
   */
  public String getEnd()
  {
    StringBuilder sb=new StringBuilder();
    sb.append("</").append(m_topElement).append(">");
    return sb.toString();
  }
  
}
